package com.whjz.dcfs.util;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 提供公共方法的action类
 * 创建时间: 2012-05-03
 */
public class BaseAction extends ActionSupport {

	private static final long serialVersionUID = 4363572172849229047L;
	
	/**
	 * 获得Session
	 */
	public Map<String, Object> getSession() {
		return ActionContext.getContext().getSession();
	}

	/**
	 * 获得ActionContext
	 */
	public ActionContext getActionContext() {
		return ActionContext.getContext();
	}
	
	/**
	 * 获得HttpServletRequest
	 */
	public HttpServletRequest getHttpServletRequest() {
		return ServletActionContext.getRequest();
	}
	
	/**
	 * 获得HttpServletResponse
	 */
	public HttpServletResponse getHttpServletResponse() {
		return ServletActionContext.getResponse();
	}
	
	/**
	 * 获得HttpSession
	 */
	public HttpSession getHttpSession() {
		return getHttpServletRequest().getSession();
	}
	
	/**
	 * 获得ServletContext
	 */
	public ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	
	/**
	 * 获得cookies
	 */
	public Cookie[] getCookies() {
		return getHttpServletRequest().getCookies();
	}
	
	/**
	 * 设置cookie
	 * @param name 名称
	 * @param value 值
	 * @param second 时间，以秒为单位
	 */
	public void setCookie(String name,String value,int second) {
		 Cookie cookie = new Cookie(name, value);
         cookie.setMaxAge(second);
         cookie.setPath("/");
         getHttpServletResponse().addCookie(cookie);
	}
	
	/**
	 * 获得cookie
	 * @param name 名称
	 */
	public Cookie getCookie(String name) {
		if(StringUtils.isBlank(name)) {
			return null;
		}
		Cookie[] cookies = getCookies();
		for(Cookie cookie : cookies) {
			if(name.equals(cookie.getName())) {
				return cookie;
			}
		}
		return null;
	}
	
	/**
	 * 删除cookie
	 * @param name 名称
	 */
	public void removeCookie(String name) {
		if(StringUtils.isBlank(name)) {
			return;
		}
		for(Cookie cookie : getCookies()) {
			if(name.equalsIgnoreCase(cookie.getName())){
				cookie.setMaxAge(0);
				cookie.setPath("/");//这里可以设置域名
				getHttpServletResponse().addCookie(cookie);
			}	
		}
	}
	
}
